/*
 * Copyright (c) 2019 Wormpex.com. All Rights Reserved.
 */

package com.sk.leetcode.arithmetic;

import java.util.concurrent.CountDownLatch;

/**
 * https://leetcode-cn.com/problems/print-in-order/
 *
 * @author ke.su date: 2019-09-23 Time: 下午2:44
 */
public class Test1114 {
    private CountDownLatch second = new CountDownLatch(1);
    private CountDownLatch third = new CountDownLatch(1);

    public Test1114() {


    }

    public static void main(String[] args) throws InterruptedException {

        for (Integer i = 0; i < 100; i++) {
            //Thread.sleep(1000);
            CountDownLatch second = new CountDownLatch(1);
            CountDownLatch third = new CountDownLatch(1);

            Thread t1 = new Thread(() -> {
                System.out.print("one");
                second.countDown();
            });

            Thread t2 = new Thread(() -> {
                try {
                    second.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("two");
                third.countDown();
            });

            Thread t3 = new Thread(() -> {
                try {
                    third.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("three");
            });

            t3.start();
            t1.start();
            t2.start();


        }
    }


    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        second.countDown();
    }

    public void second(Runnable printSecond) throws InterruptedException {

        // printSecond.run() outputs "second". Do not change or remove this line.
        second.await();
        printSecond.run();
        third.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {

        // printThird.run() outputs "third". Do not change or remove this line.
        third.await();
        printThird.run();
    }

}
